package design.forkjoin;

import java.util.concurrent.RecursiveAction;
import java.util.concurrent.RecursiveTask;
import java.util.concurrent.ThreadLocalRandom;

// 递归action
public class RecuresiceAction1 extends RecursiveTask<Integer> {
    private int beginValue;
    private int endValue;

    public RecuresiceAction1(int beginValue, int endValue) {
        super();
        this.beginValue = beginValue;
        this.endValue = endValue;
    }

    @Override
    protected Integer compute() {
        System.out.println(Thread.currentThread().getName() + " start compute");
        try {
            Thread.sleep(ThreadLocalRandom.current().nextInt(2000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if((endValue - beginValue) != 0){
            // 计算中间值
            int middelNum = (beginValue + endValue) /2;
            // 左计算
            RecuresiceAction1 left = new RecuresiceAction1(beginValue,middelNum);
            // 右计算
            RecuresiceAction1 right = new RecuresiceAction1(middelNum + 1,endValue);
            // 拆解
            this.invokeAll(left,right);
            //汇总左右结果
            Integer leftRe = left.join();
            Integer rights = right.join();
            System.out.println(leftRe +" + "+ rights + "=" + (leftRe + rights));
            return leftRe + rights;

        }else{
            // 无法拆分，返回结果
            return endValue;
        }
    }
}
